//
//  WAAddNewAddressController.m
//  WalkiOS
//
//  Created by luqiuan on 2019/10/17.
//  Copyright © 2019 Chenmuzhou. All rights reserved.
//

#import "WAAddNewAddressController.h"
#import "JGProvinceManagerModel.h"
#import "JGAreaManagerPicker.h"

@interface WAAddNewAddressController ()
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

 @property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *detailAddressTF;
//只用来显示
@property (weak, nonatomic) IBOutlet UITextField *AddressTF;
@property (weak, nonatomic) IBOutlet UISwitch *defaultSwitchBtn;

@property (nonatomic, strong) NSMutableArray *dataArrM;
@end

@implementation WAAddNewAddressController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    self.nameTF.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"输入姓名" attributes:
    @{
        NSFontAttributeName:[UIFont systemFontOfSize:14],
        NSForegroundColorAttributeName:WNHexColor(0xE0E0E0)
    }];
    self.phoneTF.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"输入手机号" attributes:
    @{
        NSFontAttributeName:[UIFont systemFontOfSize:14],
        NSForegroundColorAttributeName:WNHexColor(0xE0E0E0)
    }];
    self.detailAddressTF.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"输入详细地址" attributes:
    @{
        NSFontAttributeName:[UIFont systemFontOfSize:14],
        NSForegroundColorAttributeName:WNHexColor(0xE0E0E0)
    }];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    [self returnWithTF:textField];
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField.tag == 0) {
        return YES;
    }else{
        if (textField.text.length > 18 && ![string isEqualToString:@""]) {
            return NO;
        }
        return YES;
    }
}

- (void)returnWithTF:(UITextField *)textField{
    switch (textField.tag) {
        case 0://收件人
            {
                NSLog(@"--ID:%@",textField.text);
            }
            break;
        case 1://电话
            {
                NSLog(@"--NickName:%@",textField.text);
            }
            break;
        case 2://收件地址
            {
                NSLog(@"--Sex:%@",textField.text);
            }
            break;
        case 3://详细地址
            {
                NSLog(@"--Wechat:%@",textField.text);
            }
            break;
        default:
            break;
    }
}

- (void)keyboardWillShow:(NSNotification *)notification {
    CGRect keyBoardframe = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat spaceH = 40;
        // 强迫症，不能忍警告
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wundeclared-selector"
    UITextField *tf = [self.view.window performSelector:@selector(firstResponder)];
#pragma clang diagnostic pop
    CGRect rect1 = [self.view  convertRect:tf.frame fromView:tf.superview];
    CGFloat margin = keyBoardframe.size.height + spaceH - (WNScreenHeight - CGRectGetMaxY(rect1));
    if (margin <= 0) {
        return;
    }
    [UIView animateWithDuration:0.2 animations:^{
        self.scrollView.transform = CGAffineTransformMakeTranslation(0, - margin);
    } completion:^(BOOL finished) {
    }];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    [UIView animateWithDuration:0.2 animations:^{
        self.scrollView.transform = CGAffineTransformIdentity;
    }];
}

- (IBAction)backAction:(id)sender {
    if (self.nameTF.text || self.phoneTF.text || self.detailAddressTF.text || self.AddressTF.text) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否放弃编辑" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        UIAlertAction *ensure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self popAction];
        }];
        [alertVC addAction:cancle];
        [alertVC addAction:ensure];
        [self presentViewController:alertVC animated:YES completion:nil];
    }else{
        [self popAction];
    }
    
}

//点击了收货地址选项
- (IBAction)clickAddressAction:(id)sender {
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    NSData* fileData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"area"ofType:@"json"]];
    NSArray *areaArrM = [NSJSONSerialization JSONObjectWithData:fileData options:NSJSONReadingAllowFragments error:nil];
    [self.dataArrM removeAllObjects];
    [self.dataArrM addObjectsFromArray:[JGProvinceManagerModel mj_objectArrayWithKeyValuesArray:areaArrM]];
    
    JGAreaManagerPicker *picker = [[JGAreaManagerPicker alloc] init];
    
    picker.addressArr = self.dataArrM;
    @weakify(self)
    picker.backInfo = ^(NSString * _Nonnull detailAddress, NSString * _Nonnull codes) {
        @strongify(self)
        self.AddressTF.text = detailAddress;
    };
    
    [picker showActionSheetView];
}

- (IBAction)switchAction:(id)sender {
    
}
- (IBAction)saveAction:(id)sender {
    if (self.nameTF.text.length == 0) {
        [WNTool show:@"请输入收件人姓名"];
        return;
    }
    if(![Utils isValidTelePhone:self.phoneTF.text]){
        [WNTool show:@"手机号错误"];
        return;
    }
    if (self.detailAddressTF.text.length == 0 || self.AddressTF.text.length == 0) {
        [WNTool show:@"请输入收件地址"];
        return;
    }
    [WNBusinessRequest addAddressWithID:@""
                                address:[NSString stringWithFormat:@"%@%@",self.AddressTF.text,self.detailAddressTF.text]
                              isdefault:self.defaultSwitchBtn.on
                                   name:self.nameTF.text
                                  phone:self.phoneTF.text
                                   Succ:^(id  _Nonnull responseObject) {
        [WNTool show:@"新增地址成功"];
        [self popAction];
    } fail:^(NSString * _Nonnull code, NSString * _Nonnull mes) {
        [WNTool show:mes];
    }];
}

- (NSMutableArray *)dataArrM {
    if (!_dataArrM) {
        _dataArrM = [NSMutableArray array];
    }
    return _dataArrM;
}

- (void)popAction{
    [self.navigationController popViewControllerAnimated:YES];
}
@end
